<template>
  <div class="assignment-edit">
    <a-card :bordered="false">
      <a-page-header
        :title="isEdit ? '编辑作业' : '新增作业'"
        :subtitle="isEdit ? `ID: ${assignmentData.id}` : '创建新作业模板'"
        @back="goBack"
      />
      
      <a-steps
        :current="currentStep"
        type="navigation"
        size="small"
        class="steps-navigation"
      >
        <a-step title="文档上传" />
        <a-step title="基本信息" />
        <a-step title="预览确认" />
      </a-steps>
      
      <div class="steps-content">
        <!-- 步骤1: 文档上传 -->
        <div v-if="currentStep === 0">
          <document-uploader
            :initialFileUrl="assignmentData.filePath"
            :initialFilename="getFilenameFromUrl(assignmentData.filePath)"
            @update:fileData="handleFileDataUpdate"
          />
          
          <div class="step-description">
            <a-alert type="info" show-icon>
              <template #message>使用说明</template>
              <template #description>
                <p>1. 上传作业文档（Word、PDF等格式）</p>
                <p>2. 上传完成后点击下一步继续</p>
              </template>
            </a-alert>
          </div>
        </div>
        
        <!-- 步骤2: 基本信息 -->
        <div v-if="currentStep === 1">
          <a-form 
            :model="assignmentData" 
            layout="vertical"
          >
            <a-form-item
              label="作业标题"
              name="title"
              :rules="[{ required: true, message: '请输入作业标题' }]"
            >
              <a-input 
                :value="assignmentData.title" 
                @update:value="updateTitle"
                placeholder="请输入作业标题"
                :maxLength="100"
                show-count
              />
            </a-form-item>
            
            <a-form-item
              label="作业描述"
              name="description"
            >
              <a-textarea
                :value="assignmentData.description"
                @update:value="updateDescription"
                placeholder="请输入作业描述"
                :rows="4"
                :maxLength="500"
                show-count
              />
            </a-form-item>
            
            <a-form-item
              label="AI提示词模板"
              name="aiPromptTemplate"
              :rules="[{ required: true, message: '请输入AI提示词模板' }]"
            >
              <a-alert
                type="info"
                message="提示"
                description="请输入AI提示词模板，用于指导AI批阅方向"
                show-icon
                style="margin-bottom: 8px;"
              />
              <a-textarea
                :value="assignmentData.aiPromptTemplate"
                @update:value="updateAiPromptTemplate"
                placeholder="请输入AI提示词模板，例如：重点关注学生的计算过程、逻辑推理能力等"
                :rows="6"
                :maxLength="2000"
                show-count
              />
            </a-form-item>
            
            <a-form-item
              label="发布状态"
              name="isPublished"
            >
              <a-switch
                :checked="isPublishedValue"
                @update:checked="updatePublishStatus"
                :checked-children="'已发布'"
                :un-checked-children="'未发布'"
              />
            </a-form-item>
          </a-form>
        </div>
        
        <!-- 步骤3: 预览确认 -->
        <div v-if="currentStep === 2">
          <a-form layout="vertical">
            <a-row :gutter="16">
              <a-col :span="24">
                <a-card title="作业预览" class="preview-card">
                  <a-descriptions bordered :column="1">
                    <a-descriptions-item label="作业标题">
                      {{ assignmentData.title }}
                    </a-descriptions-item>
                    <a-descriptions-item label="作业描述">
                      {{ assignmentData.description || '无' }}
                    </a-descriptions-item>
                    <a-descriptions-item label="AI提示词模板">
                      {{ assignmentData.aiPromptTemplate || '无' }}
                    </a-descriptions-item>
                    <a-descriptions-item label="发布状态">
                      <a-tag :color="assignmentData.isPublished === 1 ? 'green' : 'orange'">
                        {{ assignmentData.isPublished === 1 ? '已发布' : '未发布' }}
                      </a-tag>
                    </a-descriptions-item>
                    <a-descriptions-item label="作业文档">
                      <a v-if="assignmentData.filePath" :href="assignmentData.filePath" target="_blank">
                        {{ getFilenameFromUrl(assignmentData.filePath) || '下载作业文档' }}
                      </a>
                      <span v-else>无</span>
                    </a-descriptions-item>
                  </a-descriptions>
                </a-card>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>
      
      <div class="steps-action">
        <a-space>
          <a-button 
            v-if="currentStep > 0" 
            @click="prevStep"
          >
            上一步
          </a-button>
          <a-button 
            v-if="currentStep < 2" 
            type="primary" 
            @click="nextStep"
            :disabled="isStepDisabled"
          >
            下一步
          </a-button>
          <a-button
            v-if="currentStep === 2"
            type="primary"
            :loading="submitting"
            @click="handleSubmit"
          >
            {{ isEdit ? '更新作业' : '创建作业' }}
          </a-button>
          <a-button v-if="isEdit" @click="goBack">取消</a-button>
        </a-space>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts">
import { ref, reactive, computed, defineComponent, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import DocumentUploader from './components/DocumentUploader.vue'
import { 
  getAssignmentTemplate, 
  createAssignmentTemplate, 
  updateAssignmentTemplate 
} from '@/api/assignment'
import type { AssignmentTemplate } from '@/api/assignment'

export default defineComponent({
  name: 'AssignmentEdit',
  components: {
    DocumentUploader
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const currentStep = ref<number>(0)
    const submitting = ref<boolean>(false)

    // 编辑模式判断
    const isEdit = computed(() => {
      return route.params.id !== undefined
    })
    
    // Switch组件状态值
    const isPublishedValue = computed({
      get: () => assignmentData.isPublished === 1,
      set: (value: boolean) => {
        assignmentData.isPublished = value ? 1 : 0
      }
    })
    
    // 初始化作业模板数据
    const assignmentData = reactive<AssignmentTemplate>({
      id: undefined,
      title: '',
      description: '',
      isPublished: 0,
      filePath: '',
      aiPromptTemplate: ''
    })
    
    // 监听路由参数，获取作业模板详情
    onMounted(async () => {
      if (isEdit.value && route.params.id) {
        try {
          const res = await getAssignmentTemplate(route.params.id as string)
          if (res.code === 200 && res.data) {
            // 更新作业模板数据
            Object.assign(assignmentData, res.data)
          } else {
            message.error(res.message || '获取作业模板详情失败')
          }
        } catch (error) {
          message.error('获取作业模板详情失败')
        }
      }
    })
    
    // 从URL中获取文件名
    const getFilenameFromUrl = (url?: string) => {
      if (!url) return ''
      try {
        return url.split('/').pop() || ''
      } catch {
        return ''
      }
    }
    
    // 处理文件数据更新
    const handleFileDataUpdate = (data: { url: string, filename: string }) => {
      assignmentData.filePath = data.url
    }
    
    // 当前步骤是否禁用下一步
    const isStepDisabled = computed(() => {
      if (currentStep.value === 0) {
        return !assignmentData.filePath
      }
      if (currentStep.value === 1) {
        return !assignmentData.title || !assignmentData.aiPromptTemplate
      }
      return false
    })

    // 下一步
    const nextStep = () => {
      // 进行表单校验
      if (currentStep.value === 0 && !assignmentData.filePath) {
        message.warning('请先上传文档')
        return
      }
      
      if (currentStep.value === 1 && !assignmentData.title) {
        message.warning('请输入作业标题')
        return
      }
      
      if (currentStep.value === 1 && !assignmentData.aiPromptTemplate) {
        message.warning('请输入AI提示词模板')
        return
      }
      
      if (currentStep.value < 2) {
        currentStep.value++
      }
    }

    // 上一步
    const prevStep = () => {
      if (currentStep.value > 0) {
        currentStep.value--
      }
    }

    // 返回列表页
    const goBack = () => {
      router.push('/assignment')
    }

    // 提交表单
    const handleSubmit = async () => {
      // 表单校验
      if (!assignmentData.title) {
        message.warning('请输入作业标题')
        currentStep.value = 1
        return
      }
      
      if (!assignmentData.aiPromptTemplate) {
        message.warning('请输入AI提示词模板')
        currentStep.value = 1
        return
      }
      
      try {
        submitting.value = true
        
        // 根据是否编辑模式选择创建或更新接口
        const apiFunc = isEdit.value ? updateAssignmentTemplate : createAssignmentTemplate
        const res = await apiFunc(assignmentData)
        
        if (res.code === 200) {
          message.success(isEdit.value ? '作业模板更新成功' : '作业模板创建成功')
          router.push('/assignment')
        } else {
          message.error(res.message || (isEdit.value ? '作业模板更新失败' : '作业模板创建失败'))
        }
      } catch (error) {
        message.error(isEdit.value ? '更新作业模板失败' : '创建作业模板失败')
      } finally {
        submitting.value = false
      }
    }

    // 更新作业标题
    const updateTitle = (value: string) => {
      assignmentData.title = value
    }

    // 更新作业描述
    const updateDescription = (value: string) => {
      assignmentData.description = value
    }

    // 更新AI提示词模板
    const updateAiPromptTemplate = (value: string) => {
      assignmentData.aiPromptTemplate = value
    }

    // 更新发布状态
    const updatePublishStatus = (value: boolean) => {
      assignmentData.isPublished = value ? 1 : 0
    }

    return {
      currentStep,
      submitting,
      isEdit,
      isPublishedValue,
      assignmentData,
      nextStep,
      prevStep,
      goBack,
      handleSubmit,
      getFilenameFromUrl,
      handleFileDataUpdate,
      isStepDisabled,
      updateTitle,
      updateDescription,
      updatePublishStatus,
      updateAiPromptTemplate
    }
  }
})
</script>

<style scoped>
.assignment-edit {
  padding-bottom: 24px;
}

.steps-navigation {
  margin-bottom: 24px;
}

.steps-content {
  min-height: 300px;
  padding: 24px;
  margin-top: 16px;
  margin-bottom: 24px;
  background-color: #fafafa;
  border: 1px dashed #e9e9e9;
  border-radius: 2px;
}

.steps-action {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.step-description {
  margin-top: 24px;
}

.preview-card {
  margin-bottom: 24px;
}

.preview-content {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
  margin-top: 8px;
}

.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3) {
  margin-top: 16px;
  margin-bottom: 8px;
}

.markdown-content :deep(p) {
  margin-bottom: 12px;
}

.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  padding-left: 20px;
  margin-bottom: 12px;
}

.markdown-content :deep(pre) {
  background-color: #f0f0f0;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  margin-bottom: 12px;
}

.markdown-content :deep(code) {
  font-family: 'Courier New', Courier, monospace;
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 2px;
}

.markdown-content :deep(blockquote) {
  border-left: 4px solid #ddd;
  padding-left: 16px;
  margin-bottom: 12px;
  color: #666;
}
</style> 